package com.jason.platform.supervision.activity;

import android.os.Bundle;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.hzlj.supervision.changsha.R;
import com.jason.platform.supervision.AppManager;
import com.jason.platform.supervision.base.Config;
import com.jason.platform.supervision.base.EventBusParameter;
import com.jason.platform.supervision.base.WeakReferenceHandler;
import com.jason.platform.supervision.widght.LoadingDialog;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

import java.lang.reflect.Field;

/**
 * @ClassName: BaseActivity
 * @Description: BaseActivity 基类Activity
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2015-7-25 06:57:14
 */
public abstract class BaseActivity extends FragmentActivity {

    public ViewGroup mDecorView;

    public boolean mHasNextPage = false;//是否有分页

    public boolean mIsLoading = false;//当前数据是否在加载

    public boolean mIsStart = true;//是否是第一次调用接口

    public int mCurrentIndex = 0;//当前页码

    public LoadingDialog mLoadingDialog;

    abstract void handleMessage(BaseActivity activity, Message msg);

    static class MyHandler<T> extends WeakReferenceHandler<T> {

        public MyHandler(T reference) {
            super(reference);
        }

        @Override
        protected void handleMessage(T reference, Message msg) {
            BaseActivity activity = (BaseActivity) reference;
            activity.handleMessage(activity, msg);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppManager.getAppManager().addActivity(this);
        /***
         * 1、onEvent ：如果使用onEvent作为订阅函数，那么该事件在哪个线程发布出来的，onEvent就会在这个线程中运行，也就是说发布事件和接收事件线程在同一个线程。使用这个方法时，在onEvent方法中不能执行耗时操作，如果执行耗时操作容易导致事件分发延迟。
         * 2、onEventMainThread ：如果使用onEventMainThread作为订阅函数，那么不论事件是在哪个线程中发布出来的，onEventMainThread都会在UI线程中执行，接收事件就会在UI线程中运行，这个在Android中是非常有用的，因为在Android中只能在UI线程中跟新UI，所以在onEvnetMainThread方法中是不能执行耗时操作的。
         * 3、onEventBackgroundThread ：如果使用onEventBackgrond作为订阅函数，那么如果事件是在UI线程中发布出来的，那么onEventBackground就会在子线程中运行，如果事件本来就是子线程中发布出来的，那么onEventBackground函数直接在该子线程中执行。
         * 4、onEventAsync：使用这个函数作为订阅函数，那么无论事件在哪个线程发布，都会创建新的子线程在执行onEventAsync.
         */
        EventBus.getDefault().register(this);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .detectAll()
                    .penaltyLog()
                    .penaltyDialog()
                    .detectDiskReads()
                    .detectDiskWrites()
                    .detectNetwork().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        getDeviceDensity();
        // 沉浸模式
        if (android.os.Build.VERSION.SDK_INT > 18) {
            Window window = getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            //设置根布局的内边距
            ViewGroup relativeLayout = (ViewGroup) findViewById(R.id.container);
            relativeLayout.setPadding(0, getStatusBarHeight(), 0, 0);

            // 创建TextView
            TextView textView = new TextView(this);
            LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, getStatusBarHeight());
            textView.setBackgroundColor(getResources().getColor(R.color.status_bar_bg));

            textView.setLayoutParams(lParams);
            // 获得根视图并把TextView加进去。
            mDecorView = (ViewGroup) getWindow().getDecorView();
            mDecorView.addView(textView);
        }
        initLoadingDialog();
        initWidget();
        initData();
    }

    @Subscribe
    public void onEventBackground(EventBusParameter parameter) {
        onEventRunBackground(parameter);
    }

    protected void onEventRunBackground(EventBusParameter parameter) {

    }

    //初始化控件
    protected void initWidget() {

    }

    //初始化数据
    protected void initData() {

    }

    //初始化等待框
    protected void initLoadingDialog() {

    }

    /**
     * 获取当前设备的屏幕密度等基本参数
     */
    protected void getDeviceDensity() {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        Config.DENSITY = metrics.density;
        Config.EXACT_SCREEN_HEIGHT = metrics.heightPixels;
        Config.EXACT_SCREEN_WIDTH = metrics.widthPixels;
    }

    // 获取手机状态栏高度
    public int getStatusBarHeight() {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        // TODO Auto-generated method stub
        super.onWindowFocusChanged(hasFocus);
        if (android.os.Build.VERSION.SDK_INT > 18) {
            if (hasFocus) {
                mDecorView.setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册EventBus
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }
}
